//
//  ZYReturnRedbagVC.swift
//  HengYouCai
//
//  Created by lwj on 2018/6/14.
//  Copyright © 2018年 lwj. All rights reserved.
//

import UIKit

class ZYReturnRedbagVC: BaseTableViewController {
    
    ///上拉下拉刷新管理器
    let pageManager = JCWRefreshPageManager()
    var redIsValid: Bool = true
    
    var titleName:String?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.createNav()
        self.createCV()
    }
    
    func createNav() {
        self.navigationItem.title =  self.titleName //"投资红包"
        
        let btn = UIButton(type: .custom)
        btn.setTitle("规则说明", for: .normal)
        btn.setTitleColor(Normal_333Color, for: .normal)
        btn.titleLabel?.font=Font_WL(14);
        btn.sizeToFit()
        btn.addTarget(self, action: #selector(rightNavClick), for: .touchUpInside)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btn)
    }
    
    @objc fileprivate func rightNavClick(){
        if let vc = BannerWebViewVC(urlStr: JCW_RedbagRuler, title: "规则说明"){
            self.pushVC(vc)
        }
    }
    
    func createCV(){
        self.view.backgroundColor = BgView_f3f3f3Color
        self.tableView.separatorStyle = .none
        self.tableView.tableHeaderView = self.headerView
        self.tableView.rowHeight = 122
        self.tableView.tableFooterView = self.footerView
        
        self.view.jcw_showGifLoading()
        
        //下拉刷新
        weak var weakSelf = self
        self.tableView.mj_header = LWRefreshGifHeader(refreshingBlock: {
            weakSelf?.pageManager.pageNo = 1
            weakSelf?.loadData()
        })
        self.loadData()
    }
    

    // mark：表头表尾
    lazy var headerView: UIView = {
        
        let temp = UIView(frame: CGRect(x: 0, y: 0, width: JCWSCREENW, height: 10))
        let cv = UIView(frame: CGRect(x: 15, y: 7.5, width: JCWSCREENW - 30, height:73))
        cv.backgroundColor = UIColor.white
//        temp.addSubview(cv)
        
        let labW: CGFloat = cv.width_sd/2
        let labH: CGFloat = cv.height_sd
        
        //左文字
        let leftLab = UILabel(frame: CGRect(x: 0, y: 0, width: labW, height: labH))
        leftLab.tag = 1000
        leftLab.textAlignment = .center
        leftLab.numberOfLines = 2
        cv.addSubview(leftLab)
        
        //右边文字
        let rightLab = UILabel(frame: CGRect(x: labW, y: 0, width: labW, height: labH))
        cv.addSubview(rightLab)
        rightLab.tag = 1001
        rightLab.textAlignment = .center
        rightLab.numberOfLines = 2
        cv.addSubview(rightLab)
        
        //分割线
        let sep = UIView(frame: CGRect(x: 0, y: 20.5, width: 0.5, height: 32))
        sep.backgroundColor = Normal_999Color
        sep.centerX_sd = labW
        cv.addSubview(sep)
        
        return temp
        
        
    }()
    
    lazy var footerView: UIView = {
        
        let temp = UIView(frame: CGRect(x: 0, y: 0, width: JCWSCREENW, height: 80))
        let leftLabel = UILabel()
        leftLabel.text = "已无更多可用红包"
        leftLabel.font = UIFont.systemFont(ofSize: 12)
        leftLabel.textColor = Normal_999Color
        leftLabel.textAlignment = .right
        leftLabel.frame = CGRect(x: 0, y: 30, width: JCWSCREENW*0.5-5, height: 20)
        temp.addSubview(leftLabel)
        let btn = UIButton(type: .system)
        btn.tag = 1002
        btn.contentHorizontalAlignment = .left
        btn.frame = CGRect(x: JCWSCREENW*0.5-10, y: 30, width: JCWSCREENW*0.5-10, height: 20)
        btn.addTarget(self, action: #selector(footerViewClick), for: .touchUpInside)
        temp.addSubview(btn)
        return temp
    }()
    
    @objc fileprivate func footerViewClick(){
        self.redIsValid = !self.redIsValid
        self.pageManager.pageNo = 1
        view.showHUDLoading()
        self.loadData()
    }
}

// mark：表代理
extension ZYReturnRedbagVC{
    
    override func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
        return self.pageManager.dataArr.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> ZYReturnRedbagVCCell {
            let cell = ZYReturnRedbagVCCell.wl_createCellWithTableView(tableView)
            cell.wl_configurationCell(self.pageManager.dataArr, tableView, indexPath)
            return cell
        }
}

extension ZYReturnRedbagVC {
    
    fileprivate func loadData(){
        HYCNetService.myWalletMyredPackList(withDict:
            ["type":"0","flag":self.redIsValid ?"ksy":"ysx","pageNo":self.pageManager.pageNo,"pageSize":self.pageManager.pageSize], onSuccess: { (resultDic) in
            
            // 隐藏加载框
            self.view.hideHUDLoading(0)
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            
            // 空置直接返回 防止转化json crash
            if let result = resultDic,result.isEmpty{return}
            
            // 处理头部文字
            self.handleHeaderText(resultDic?["balanceSum"] as? String ?? "", resultDic?["consumedSum"] as? String ?? "")
            let resultList: [Any]? = JSON(resultDic as Any).dictionaryValue["myredPackList"]?.arrayObject
            
            if self.pageManager.pageNo == JCWLimitNumberStarPage{
                self.pageManager.dataArr.removeAll()
            }
            
            if let count = resultList?.count, count >= JCWLimitNumberPageSize{
                self.pageManager.pageNo += JCWLimitNumberStarPage
                weak var weakSelf = self
                self.tableView.mj_footer = JCWRefreshFooter(refreshingBlock: {
                    weakSelf?.loadData()
                })
                
                // 处理尾部文字，有更多
                self.handleFooterText("",self.redIsValid ? "查看已用完/已过期" : "查看可使用")
            }
            else
            {
                
                // 无更多 处理尾部文字
                self.handleFooterText("",self.redIsValid ? "查看已用完/已过期": "查看可使用")
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
            }
            self.pageManager.dataArr.append(contentsOf: RedPackModel.mj_objectArray(withKeyValuesArray: resultList))
            
            self.tableView.reloadData()
            
        }) { (code, errMsg) in
            self.tableView.mj_footer?.endRefreshing()
            self.tableView.mj_header.endRefreshing()
            self.view.showHUDFailTips(errMsg, hideDelay: kHUDHideDelay)
        }
        
    }
    
    private func handleFooterText(_ str1: String, _ str2: String){
        if let btn = self.footerView.viewWithTag(1002) as? UIButton{
            let text = NSMutableAttributedString(string: str1, attributes:[NSFontAttributeName:Font_WL(12),NSForegroundColorAttributeName:Normal_999Color])
            text.append(NSAttributedString(string: str2, attributes:[NSFontAttributeName:Font_WL(12),NSForegroundColorAttributeName:Normal_BlueColor]))
            btn.setAttributedTitle(text, for: .normal)
        }
    }
    
    private func handleHeaderText(_ leftStr: String, _ rightStr: String){
        if let leftLab = self.headerView.viewWithTag(1000) as? UILabel, let rightLab=self.headerView.viewWithTag(1001) as? UILabel{
            
            let text1 = NSMutableAttributedString(string: "可用红包总额(元)\n", attributes: [NSFontAttributeName:Font_WL(13.aw_wl),NSForegroundColorAttributeName:Normal_333Color])
            text1.append(NSAttributedString(string: leftStr, attributes:                [NSFontAttributeName:Font_WL(16.aw_wl),NSForegroundColorAttributeName:Normal_RedColor]))
            
            let text2 = NSMutableAttributedString(string: "已返现金额(元)\n", attributes:                [NSFontAttributeName:Font_WL(13.aw_wl),NSForegroundColorAttributeName:Normal_333Color])
            text2.append(NSAttributedString(string:rightStr, attributes:                [NSFontAttributeName:Font_WL(16.aw_wl),NSForegroundColorAttributeName:Normal_RedColor]))
            leftLab.attributedText = text1
            rightLab.attributedText = text2
        }
    }
    
}

















